﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor.TreeMapCompiler
{
    internal class _MapCompiler
    {
        public static string CompileTreeMaps(string htmlBody, ref MarkdownSharp.Markdown md)
        {
            var lines = htmlBody.Split(new string[] { "\r\n", }, StringSplitOptions.None);

            var result = new StringBuilder();
            bool treeIsOpen = false;
            var sb = new StringBuilder();
            var mark = "";

            var regex = new Regex(@"[\[【][ 　\t]*?((li?st)|([ 　\t]*?[\<\>]?[ 　\t]*?org))[ 　\t]*?[\]】]", RegexOptions.IgnoreCase);
            foreach (var line in lines)
            {
                if (CustomMarkdownSupport.IsTreeListTextLine(line, out string header, out string tail, out int level))
                {
                    var match = regex.Match(tail);
                    if (match.Success)
                    {
                        var txt = match.Value.ToLower();

                        if (txt.Contains("list") || txt.Contains("lst"))
                        {
                            mark = "[list]";
                        }
                        else if (txt.Contains("org"))
                        {
                            mark = "[org]";
                        }

                        if (treeIsOpen == false)
                        {
                            sb.Clear();
                            treeIsOpen = true;
                        }
                    }

                    if (treeIsOpen)
                    {
                        sb.Append(line);
                        sb.Append("\r\n");
                    }
                    else
                    {
                        result.Append(line);
                        result.Append("\r\n");
                    }
                }
                else
                {
                    if (treeIsOpen)
                    {
                        if (sb.Length > 0)
                        {
                            if (mark == "[list]" || mark == "[lst]")
                            {
                                result.Append(ListMapCompiler.Run(sb.ToString(), ref md) + "\r\n");
                            }
                            else if (mark == "[org]")
                            {
                                result.Append(OrgMapCompiler.Run(sb.ToString(), ref md) + "\r\n");
                            }
                        }
                        treeIsOpen = false;
                        mark = "";
                    }

                    result.Append(line);
                    result.Append("\r\n");
                }
            }

            return result.ToString();
        }
    }
}
